package org.ytor.core.webmbc;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.ytor.common.util.Jsons;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * created by yangtong on 2025/5/27 15:55:00
 * <br/>
 * jackson配置
 */
@Configuration
public class JacksonConfig {


    @Autowired
    public void autowired(@Lazy ObjectMapper objectMapper) {
        Jsons.register(objectMapper);
    }

    /**
     * 使用asm技术优化jackson
     */
    @Bean
    public AfterburnerModule afterburnerModule() {
        //Spring Boot会自动将ioc中的Module注册给ObjectMapper
        return new AfterburnerModule();
    }

    /**
     * 数组类型的null字段，不返回null而是返回空数组
     */
    @Bean
    public SimpleModule emptyArrayModule() {
        SimpleModule module = new SimpleModule("EmptyArrayModule");
        module.setSerializerModifier(new BeanSerializerModifier() {
            @Override
            public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                             BeanDescription beanDesc, List<BeanPropertyWriter> props) {
                for (BeanPropertyWriter writer : props) {
                    JavaType type = writer.getType();
                    Class<?> raw = type.getRawClass();
                    if (Collection.class.isAssignableFrom(raw) || raw.isArray()) {
                        writer.assignNullSerializer(new JsonSerializer<>() {
                            @Override
                            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
                                    throws IOException {
                                gen.writeStartArray();
                                gen.writeEndArray();
                            }
                        });
                    }
                }
                return props;
            }
        });
        return module;
    }

}
